import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Mapper {
    public static void main(String[] args) {
        try {
            Sender sender = Sender.getInstance();
            String filePath = Utilbll.projectDir() + "1.txt";
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            String tmp;
            HashMap<String, Integer> mapContent = new HashMap<>();
            while ((tmp = br.readLine()) != null) {
                for (String s : tmp.split(" ")) {
                    if (mapContent.containsKey(s)) {
                        int tmpCount = mapContent.get(s);
                        mapContent.put(s, tmpCount + 1);
                    } else {
                        mapContent.put(s, 1);
                    }
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.putAll(mapContent);
            int countSenders = 3;
            int countReceivers = Utilbll.getProperty("RECEIVE_IP").split(",").length;
            ExecutorService pool = Executors.newFixedThreadPool(countSenders);
            for (int i = 0; i < countSenders; i++) {
                sender.connect(i % countReceivers);
                MultiSender multiSender = new MultiSender(jsonObject.toJSONString(),sender);
                pool.submit(multiSender);
            }
            pool.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static class MultiSender implements Callable<Object> {
        public String jsonMap;
        public Sender sender;

        public MultiSender(String jsonMap, Sender sender) {
            this.jsonMap = jsonMap;
            this.sender = sender;
        }

        public Object call() {
            sender.send(jsonMap);
            return null;
        }
    }
}
